<template>
  <section id="iProject">
    <section class="label">当前工程：</section>
    <el-select v-model="id" @change="saveProject">
      <el-option v-for="project in data" :key="project.id" :label="project.name" :value="project.id"></el-option>
    </el-select>
  </section>
</template>

<script>
import * as api from '../api/public/iProject'
import * as storage from '../utils/storage'
export default {
  name: 'iProject',
  data: () => ({
    data: [],
    id: ''
  }),
  methods: {
    async getProject() {
      const data = await api.getProject()
      if (data.code === 0) {
        this.data = data.data
        this.setProject()
      } else {
        this.$msg.error(data.msg)
      }
    },
    setProject() {
      const id = storage.get(JSON.parse(storage.get(true, 'remember_me')), 'project_id')
      if (this.data.findIndex(project => project.id === id) !== -1) {
        this.id = id
        this.submitAndBroadcast(id)
      }
    },
    //  保存项目ID到本地，并广播给当前存活的组件
    saveProject(data) {
      storage.set(JSON.parse(storage.get(true, 'remember_me')), 'project_id', data)
      this.submitAndBroadcast(data)
    },
    submitAndBroadcast(id) {
      this.$store.commit('setProjectID', id)
      this.$ebs.$emit('project_change', id)
    }
  },
  created() {
    this.getProject()
  },
  mounted() {
    //  监听项目新建事件
    this.$ebs.$on('project_created', () => {
      this.getProject()
    })

    this.$ebs.$on('reload_project', (data) => {
      console.log(data,'1111');
      if(data.id === this.id) this.id = ''
      this.getProject()
    })
  }
}
</script>

<style lang="scss" scoped>
#iProject {
  height: 100%;
  display: flex;
  align-items: center;

  .label {
    font-size: 1.05rem;
    font-weight: bold;
    white-space: nowrap;
  }
}
</style>
